package com.hrc.springbootdemo.ws.handler;

import com.hrc.springbootdemo.ws.service.WebSocketService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;


@Component
@Slf4j
public class ToClientMessageWebsocketHandler implements WebSocketHandler {

    @Resource
    private WebSocketService webSocketService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("客户端连接成功");
        webSocketService.handleOpen(session);
        webSocketService.sendMessage(session, "服务端：连接成功");
    }


    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String messages = message.getPayload().toString();
        log.info("服务端收到消息：{}", messages);
        webSocketService.handleMessage(session, messages);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.sendMessage(new TextMessage(exception.getMessage()));
        webSocketService.handleError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
           webSocketService.handleClose(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
